import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:flutter_aygsh/http/Api.dart';
import '../util/SignUtil.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import '../liz_home/goods/BrandDetail.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_header.dart';

class BandCate extends StatefulWidget {
  BandCate({Key key}) : super(key: key);

  @override
  _BandCateState createState() => _BandCateState();
}

class _BandCateState extends State<BandCate>
    with AutomaticKeepAliveClientMixin {
  int _selectIndex = 0;
  Map _list = {};
  List _leftCateList = [];
  List _rightCateList = [];
  EasyRefreshController _controller = EasyRefreshController();

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    initData();
  }

  initData() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_BRAND_LISTBYLETTER),
    });

    // FormData data = new FormData.fromMap({});
    Response<String> response =
        await HttpUtil().post(Api.URL_BRAND_LISTBYLETTER, data: getSign(map));
    Map userMap = json.decode(response.data);
    Map pp = userMap['data']['list'];
    // print('品牌');
    // print(pp);
    _leftCateList.clear();
    pp.forEach((k, v) {
      if (v.length > 0) {
        Map map = new Map();
        map['name'] = k;
        map['child'] = v;

        _leftCateList.add(map);
      }
    }); //打印所有的value
    print(_leftCateList);
    if (userMap['code'] == 1) {
      _controller.finishRefresh();
      if (mounted) {
        setState(() {
          _list = pp;
        });
        // print(_list.length);
      }
    }
  }

  // _getRightCateData(String key) {
  //   setState(() {
  //     _rightCateList.clear();
  //     _rightCateList.addAll(_list[key]);
  //   });
  // }

  //左侧组件
  Widget _leftCateWidget(leftWidth) {
    if (this._list.length > 0) {
      return Container(
        width: leftWidth,
        height: double.infinity,
        // color: Colors.red,
        child: ListView.builder(
          itemCount: this._leftCateList.length,
          itemBuilder: (context, index) {
            return Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    // setState(() {
                    //   _selectIndex = index;
                    //   print('左边');
                    //   print(this._leftCateList[index]);
                    //   this._getRightCateData(this._leftCateList[index]);
                    // });
                  },
                  child: Container(
                    width: double.infinity,
                    height: ScreenUtil().setHeight(70),
                    padding: EdgeInsets.all(kMargin20),
                    child: Text(
                      '22',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)),
                    ),
                    color: _selectIndex == index
                        ? Color.fromRGBO(240, 246, 246, 0.9)
                        : Colors.white,
                  ),
                ),
                Divider(height: 1),
              ],
            );
          },
        ),
      );
    } else {
      return Container(
        width: leftWidth,
        height: double.infinity,
      );
    }
  }

  // //右侧组件：
  // Widget _rightCateWidget(rightItemWidth, rightItemHeigth) {
  //   if (this._rightCateList.length > 0) {
  //     return Expanded(
  //       flex: 1,
  //       child: Container(
  //         padding: EdgeInsets.all(10),
  //         height: double.infinity,
  //         color: Color.fromRGBO(240, 246, 246, 0.9),
  //         // color: Colors.blue,
  //         child: GridView.builder(
  //           gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  //               crossAxisCount: 3,
  //               childAspectRatio: rightItemWidth / rightItemHeigth,
  //               crossAxisSpacing: kMargin20 * 4,
  //               mainAxisSpacing: kMargin20 * 3),
  //           itemCount: this._rightCateList.length,
  //           itemBuilder: (context, index) {
  //             return GestureDetector(
  //                 onTap: () {
  //                   print(this._rightCateList[index]);
  //                   Navigator.of(context)
  //                       .push(new MaterialPageRoute(builder: (context) {
  //                     return new BrandDetailPage(
  //                       brand_id:
  //                           this._rightCateList[index]['brand_id'].toString(),
  //                     );
  //                   }));
  //                 },
  //                 child: Container(
  //                   // padding: EdgeInsets.all(ScreenAdaper.width(20)),
  //                   child: Column(
  //                     children: <Widget>[
  //                       ClipOval(
  //                           // child:
  //                           child: this._rightCateList[index]['logo'] == null ||
  //                                   this._rightCateList[index]['logo'] == ''
  //                               ? Image.asset('images/logo.png',
  //                                   width: ScreenUtil.getInstance()
  //                                       .setWidth(DP_90),
  //                                   height: ScreenUtil.getInstance()
  //                                       .setWidth(DP_90))
  //                               : CachedNetworkImage(
  //                                   width: ScreenUtil.getInstance()
  //                                       .setWidth(DP_90),
  //                                   height: ScreenUtil.getInstance()
  //                                       .setWidth(DP_90),
  //                                   imageUrl: Api.BaseUrl +
  //                                       'public/upload/' +
  //                                       this
  //                                           ._rightCateList[index]['logo']
  //                                           .replaceAll('\\', '/'),
  //                                   placeholder: (context, url) => Image.asset(
  //                                       'images/logo.png',
  //                                       width: ScreenUtil.getInstance()
  //                                           .setWidth(DP_90),
  //                                       height: ScreenUtil.getInstance()
  //                                           .setWidth(DP_90)),
  //                                   errorWidget: (context, url, error) =>
  //                                       Image.asset('images/logo.png',
  //                                           width: ScreenUtil.getInstance()
  //                                               .setWidth(DP_90),
  //                                           height: ScreenUtil.getInstance()
  //                                               .setWidth(DP_90)),
  //                                 )),
  //                       Container(
  //                         height: ScreenUtil().setHeight(32),
  //                         child: Text("${this._rightCateList[index]['name']}",
  //                             style: TextStyle(
  //                                 fontSize: ScreenUtil.getInstance()
  //                                     .setSp(SMALL_FONT_SIZE))),
  //                       )
  //                     ],
  //                   ),
  //                 ));
  //           },
  //         ),
  //       ),
  //     );
  //   } else {
  //     return Expanded(
  //         flex: 1,
  //         child: Container(
  //           padding: EdgeInsets.all(10),
  //           height: double.infinity,
  //           color: Color.fromRGBO(240, 246, 246, 0.9),
  //           child: Center(child: Text('暂无')),
  //         ));
  //   }
  // }

  Widget build(BuildContext context) {
    //计算右侧GridView宽高比：
    var leftWidth = ScreenUtil.getInstance().setWidth(750) / 4 * 3;
    //右侧宽高=总宽度-左侧宽度-Gridview外层元素左右的Padding值-GridView中间的间距
    var rightItemWidth =
        (ScreenUtil.getInstance().setWidth(750) - leftWidth - 20 - 20) / 3;
    rightItemWidth = ScreenUtil().setWidth(rightItemWidth);
    var rightItemHeigth = rightItemWidth + ScreenUtil().setHeight(32);

    return Scaffold(
        body: Container(
            child: new EasyRefresh(
      enableControlFinishRefresh: true,
      // taskIndependence: true,
      controller: _controller,
      header: MaterialHeader(),
      child:
          //  Row(
          //   children: <Widget>[
          // _leftCateWidget(leftWidth),
          ListView.builder(
        itemCount: _leftCateList.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.all(ScreenUtil.getInstance().setWidth(20)),
                width: ScreenUtil.getInstance().setWidth(750),
                height: ScreenUtil.getInstance().setWidth(80),
                color: white,
                child: Text(
                  _leftCateList[index]['name'],
                  style: TextStyle(
                      color: mainColor,
                      fontSize: ScreenUtil.getInstance().setSp(30),fontWeight: FontWeight.w500),
                ),
              ),
              ListView.builder(
                  shrinkWrap: true, //为true可以解决子控件必须设置高度的问题
                  physics: NeverScrollableScrollPhysics(), //禁用滑动事件
                  itemCount: _leftCateList[index]['child'].length,
                  itemBuilder: (context, index2) {
                    return GestureDetector(
                  onTap: () {
                    // print(this._rightCateList[index]);
                    Navigator.of(context)
                        .push(new MaterialPageRoute(builder: (context) {
                      return new BrandDetailPage(
                        brand_id:
                            this._leftCateList[index]['child'][index2]['brand_id'].toString(),
                      );
                    }));
                  },
                  child:Container(
                      padding: EdgeInsets.all(ScreenUtil.getInstance().setWidth(20)),
                      child: Text(_leftCateList[index]['child'][index2]['name'],style: TextStyle(
                         fontSize: ScreenUtil.getInstance().setSp(26)
                      ),)
                    )) ;
                  })
            ],
          );
        },
      ),
      // _rightCateWidget(rightItemWidth, rightItemHeigth)
      //   ],
      // ),
      onRefresh: () async {
        initData();
      },
    )));
  }
}
